const ora = require("ora");
const open = require("open");
const fs = require("fs-extra");
const axios = require("axios");
const path = require("path");
const execa = require("execa");
const clipboard = require('clipboardy');
const inquirer = require("inquirer");
const { ls, sleep } = require("../utils");
const spinner = ora();
const map = {
  jysq: {
    name: "jysq",
    appKey: "4",
    serviceName: "经营神器-美团",
    platform: 8,
    appKeyName: 'appKey',
    url: {
      base: "/",
      list: "/query/businessInfoList",
      login: "/occ/order/replaceUserLogin",
      userApi: "//api",
    },
    loginKey: (item) => ({
      appKey: item.appKey,
      memberId: item.shopId,
      platform: item.platform,
    }),
    testId: "15983528161",
  },
  zx: {
    name: "zx",
    appKey: "36",
    serviceName: "装修神器-美团",
    platform: 8,
    appKeyName: 'appKey',
    url: {
      base: "/",
      list: "/query/businessInfoList",
      login: "/occ/order/replaceUserLogin",
      userApi: "//api",
    },
    loginKey: (item) => ({
      appKey: item.appKey,
      memberId: item.shopId,
      platform: item.platform,
    }),
    testId: "16159400501",
  },
  ele: {
    name: "ele",
    appId: "29665924",
    appKeyName: 'appId',
    serviceName: "店客多-裂变神器",
    baseURL: "/eleocc",
    listUrl: "/manage/getOrderList",
    platform: 11,
    url: {
      base: "/eleocc",
      list: "/manage/getOrderList",
      login: "/auth/onelogin",
      userApi: "//api",
    },
    loginKey: (item) => ({
      appId: "29665924",
      shopId: item.shopId,
      userId: item.userId,
    }),
    testId: "160276429",
  },
};
map.default = map.jysq;
module.exports = async (data, options) => {
  const { shopId, match } = getMatchProject(data);
  spinner.text = "正在搜索店铺";
  let shopInfo;
  try {
    shopInfo = await getMatchShop(match, shopId);
  } catch (error) {
    spinner.fail(error);
    if (error === "登录失败") {
      await login();
      shopInfo = await getMatchShop(match, shopId);
    }
  }
  spinner.text = `获取店铺 ${shopInfo.shopName || shopInfo.shopId} 信息成功`;
  const { data: loginData } = await axios.post(
    `https://api.diankeduo.cn/zhili/${match.url.base}${match.url.login}`,
    match.loginKey(shopInfo)
  );
  const url = loginData.result;
    if (options.token) {
        const { hash } = new URL(url);
        const token = hash.replace('#/login?code=', '');
        clipboard.writeSync(token);
        spinner.succeed(
            `已复制店铺 ${shopInfo.shopName || shopInfo.shopId} 的token\n${token}`
        );
    } else if (options.pc && ['4', '36'].includes(match.appKey)) {
        // 只有美团经营神器和装修神器有PC端
        open(url.replace('app', ''));
    } else {
        open(data);
        spinner.succeed(`店铺 ${shopInfo.shopName || shopInfo.shopId} 打开成功`);
    }
};

function getMatchProject(input) {
  let match = {};
  let shopId = "";
  if (input.length === 0) {
    match = map.default;
    shopId = match.testId;
  } else if (input.length === 1) {
    if (isNaN(Number(input[0]))) {
      match = map[input[0]];
      if (!match) {
        this.spinner.fail("项目不存在，请重新输入", true);
      }
      shopId = match.testId;
    } else {
      match = map.default;
      shopId = input[0];
    }
  } else if (input.length === 2) {
    if (isNaN(Number(input[0]))) {
      match = map[input[0]];
      if (!match) {
        this.spinner.fail("项目不存在，请重新输入", true);
      }
      shopId = input[1];
    } else {
      match = map[input[1]];
      if (!match) {
        this.spinner.fail("项目不存在，请重新输入", true);
      }
      shopId = input[0];
    }
  }
  return {
    match,
    shopId,
  };
}

function getMatchShop(match, shopId) {
  return new Promise(async (resolve, reject) => {
    const res = await axios.post(
      `https://api.diankeduo.cn/zhili${match.url.base}${match.url.list}`,
      {
        [match.appKeyName]: match[match.appKeyName],
        serviceName: match.serviceName,
        platform: match.platform,
        param: shopId,
        pageSize: 1,
        pageIndex: 1
      },
      {
        headers: {
          token: ls.get("oa.token"),
        },
      }
    );
    const { data: listData } = res;
    if (listData.code !== 200) {
      reject("登录失败");
      return;
    }
    const { list } = listData.result;
    if (!list.length) {
      reject("店铺不存在");
      return;
    }
    resolve(list[0]);
  });
}

async function login() {
  // 获取验证码
  spinner.text = "token失效，需重新登录，请先输入验证码";
  const {
    data: { img, uuid },
  } = await axios.get("https://api.diankeduo.cn/zhili/captchaImage");
  const picBuffer = Buffer.from(img, "base64");
  const target = path.resolve(process.cwd(), ".temp/vrCode.png");
  await fs.writeFile(target, picBuffer);
  await execa(`code ${target}`);
  const answer = await inquirer.prompt({
    type: "input",
    message: "请输入验证码",
    name: "vrCode",
  });
  spinner.text = "正在登录";
  const { username, password } = ls.get("oa");
  const {
    data: { token },
  } = await axios.post("https://api.diankeduo.cn/zhili/login", {
    username,
    password,
    uuid,
    code: answer.vrCode,
  });
  ls.set("oa.token", token);
  await fs.remove(target);
  spinner.text = "登录成功";
  await sleep(1500);
}
